package com.example.mcp.controller;

import com.example.mcp.service.McpChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

/**
 * 聊天控制器
 * 提供REST API接口用于与MCP集成的AI进行交互
 * 
 * @author Generated
 * @version 1.0.0
 */
@RestController
@RequestMapping("/api/chat")
@CrossOrigin(origins = "*")
public class ChatController {

    @Autowired
    private McpChatService chatService;
    

    /**
     * 流式聊天接口
     * 
     * @param request 聊天请求
     * @return 流式响应
     */
    @PostMapping(value = "/stream", produces = MediaType.TEXT_PLAIN_VALUE)
    public Flux<String> streamChat(@RequestBody ChatRequest request) {
        if (request.getMessage() == null || request.getMessage().trim().isEmpty()) {
            return Flux.just("请提供有效的消息内容");
        }
        
        return chatService.chat(request.getMessage());
    }

    /**
     * 同步聊天接口
     * 
     * @param request 聊天请求
     * @return 完整响应
     */
    @PostMapping(value = "/message", produces = MediaType.APPLICATION_JSON_VALUE)
    public ChatResponse chat(@RequestBody ChatRequest request) {
        if (request.getMessage() == null || request.getMessage().trim().isEmpty()) {
            return new ChatResponse("请提供有效的消息内容", false);
        }

        try {
            // 使用AI聊天服务处理所有请求，传递 sessionId（如果没有提供，使用默认值）
            String sessionId = request.getSessionId() != null ? request.getSessionId() : "default";
            String response = chatService.chatSync(request.getMessage(), sessionId);
            return new ChatResponse(response, true);
        } catch (Exception e) {
            return new ChatResponse("处理消息时出现错误: " + e.getMessage(), false);
        }
    }

    /**
     * 清理对话历史
     * 当AI陷入错误循环时使用
     * 
     * @param sessionId 可选的会话ID，如果不提供则清理所有会话
     */
    @PostMapping(value = "/clear-history", produces = MediaType.APPLICATION_JSON_VALUE)
    public ChatResponse clearChatHistory(@RequestParam(required = false) String sessionId) {
        try {
            if (sessionId != null && !sessionId.trim().isEmpty()) {
                chatService.clearChatHistory(sessionId);
                return new ChatResponse("会话 [" + sessionId + "] 的对话历史已清理", true);
            } else {
                chatService.clearAllChatHistory();
                return new ChatResponse("所有对话历史已清理", true);
            }
        } catch (Exception e) {
            return new ChatResponse("清理对话历史失败: " + e.getMessage(), false);
        }
    }

    /**
     * 获取可用工具信息
     * 
     * @return 工具信息
     */
    @GetMapping(value = "/tools", produces = MediaType.APPLICATION_JSON_VALUE)
    public ToolsResponse getTools() {
        String toolsInfo = chatService.getAvailableTools();
        return new ToolsResponse(toolsInfo);
    }

    /**
     * 健康检查接口
     * 
     * @return 健康状态
     */
    @GetMapping(value = "/health", produces = MediaType.APPLICATION_JSON_VALUE)
    public HealthResponse health() {
        return new HealthResponse("MCP Chat Service is running", "OK");
    }

    /**
     * 聊天请求数据类
     */
    public static class ChatRequest {
        private String message;
        private String sessionId;  // 会话ID，用于区分不同的对话上下文
        
        public ChatRequest() {}
        
        public ChatRequest(String message) {
            this.message = message;
        }
        
        public ChatRequest(String message, String sessionId) {
            this.message = message;
            this.sessionId = sessionId;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public String getSessionId() {
            return sessionId;
        }

        public void setSessionId(String sessionId) {
            this.sessionId = sessionId;
        }
    }

    /**
     * 聊天响应数据类
     */
    public static class ChatResponse {
        private String response;
        private boolean success;
        private long timestamp;

        public ChatResponse() {
            this.timestamp = System.currentTimeMillis();
        }

        public ChatResponse(String response, boolean success) {
            this.response = response;
            this.success = success;
            this.timestamp = System.currentTimeMillis();
        }

        public String getResponse() {
            return response;
        }

        public void setResponse(String response) {
            this.response = response;
        }

        public boolean isSuccess() {
            return success;
        }

        public void setSuccess(boolean success) {
            this.success = success;
        }

        public long getTimestamp() {
            return timestamp;
        }

        public void setTimestamp(long timestamp) {
            this.timestamp = timestamp;
        }
    }

    /**
     * 工具响应数据类
     */
    public static class ToolsResponse {
        private String tools;
        private long timestamp;

        public ToolsResponse() {
            this.timestamp = System.currentTimeMillis();
        }

        public ToolsResponse(String tools) {
            this.tools = tools;
            this.timestamp = System.currentTimeMillis();
        }

        public String getTools() {
            return tools;
        }

        public void setTools(String tools) {
            this.tools = tools;
        }

        public long getTimestamp() {
            return timestamp;
        }

        public void setTimestamp(long timestamp) {
            this.timestamp = timestamp;
        }
    }

    /**
     * 健康检查响应数据类
     */
    public static class HealthResponse {
        private String message;
        private String status;
        private long timestamp;

        public HealthResponse() {
            this.timestamp = System.currentTimeMillis();
        }

        public HealthResponse(String message, String status) {
            this.message = message;
            this.status = status;
            this.timestamp = System.currentTimeMillis();
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }

        public long getTimestamp() {
            return timestamp;
        }

        public void setTimestamp(long timestamp) {
            this.timestamp = timestamp;
        }
    }
}
